//selectTagId:选择的标签ID（如：全部、发布。。。）,allIsLastPage:全部标签数据是不是最后一页,默认不在滚动条里加载
var fontSize = 0.4,selectTagId = 'listAllOrder', doneMsg = '您确认已完成本单任务了吗',errorTip = '当前系统繁忙，请稍候再试', defaultPageSize = 10,
    allIsLastPage = false,allCurrentPage = 1, issueIsLastPage = false,issueCurrentPage = 1,noRobIsLastPage = false,noRobCurrentPage = 1,
    robIsLastPage = false,robCurrentPage = 1,finishIsLastPage = false,finishCurrentPage = 1;
$(function(){
    listOrder('listAllOrder',1,defaultPageSize);
    var listOrderIdArray = ['listAllOrder','listIssueOrder','listNoRobOrder','listRobOrder','listFinishOrder'];
    $('.status-list span').click(function(){
        $('.status-list span').each(function(){
            $(this).removeClass('select-status');
        });
        $(this).addClass('select-status');
        for(var g = 0; g < listOrderIdArray.length; g ++){
            $('#' + listOrderIdArray[g]).hide();
        }
        $('#' + this.title).show();
        selectTagId = this.title;
        //如果没有子元素，代表还没加载，则开始加载
        if (!$('#' + this.title + ':has(div)').length){
            listOrder(this.title,1,defaultPageSize);
        }
    });
    var serviceOrderHeight = $('.service-order').height();
    //监听页面滚动条事件
    $(document).scroll(function() {
        //如果是最后一页，则不再加载
        var isNotNeedLoad = (selectTagId == 'listAllOrder' && allIsLastPage) || (selectTagId == 'listIssueOrder' && issueIsLastPage) ||
            (selectTagId == 'listNoRobOrder' && noRobIsLastPage) || (selectTagId == 'listRobOrder' && robIsLastPage) || (selectTagId == 'listFinishOrder' && finishIsLastPage);
        if (isNotNeedLoad){
            return;
        }
        //滚动高度,可见高度,内容高度
        var scrollerHeight = $(document).scrollTop(),viewHeigth = $(window).height(),contentHeigth = $(document).height();

        //距离底部高度小于3个订单DIV的高度
        if (contentHeigth - (scrollerHeight + viewHeigth) <= (serviceOrderHeight * 3)){
            console.log('aaaaaaaaaa');
            var currPage = 0;
            if (selectTagId == 'listAllOrder') {
                allCurrentPage ++;
                currPage = allCurrentPage;
            }else if (selectTagId == 'listIssueOrder'){
                issueCurrentPage ++;
                currPage = issueCurrentPage;
            }else if (selectTagId == 'listNoRobOrder'){
                noRobCurrentPage ++;
                currPage = noRobCurrentPage;
            }else if (selectTagId == 'listRobOrder'){
                robCurrentPage ++;
                currPage = robCurrentPage;
            }else if (selectTagId == 'listFinishOrder'){
                finishCurrentPage ++;
                currPage = finishCurrentPage;
            }
            listOrder(selectTagId,currPage,defaultPageSize);
        }
    });
});

/**
 * 查询移动端订单数据
 * @param currentPage  当前页号
 * @param pageSize  每页显示行数
 * @returns
 */
function listOrder(selectId,currentPage, pageSize) {
    if (isNull(sessionStorage.getItem(SCS_USER_NAME))) {
        loginConfirm();
        return;
    }
    $('#loadInfo').show();
    var issueId = '', soStatus = '', getUserId = '',statusArray = '';
    if (selectId == 'listIssueOrder' || selectId == 'listNoRobOrder') {
        issueId = sessionStorage.getItem(SCS_USER_ID);
    }else if (selectId == 'listRobOrder') {
        getUserId = sessionStorage.getItem(SCS_USER_ID);
        statusArray = '1,2,3,4';
    }else if (selectId == 'listFinishOrder') {//查询自己发布或已抢的完成的订单
        soStatus = '2';
    }
    if (selectId == 'listNoRobOrder') {
        soStatus = '0';
    }
    $.ajax({
        type: 'post',
        url: '/mServiceOrder/myAllOrder',
        dataType: 'json',
        async: false,
        timeout: 30000,
        data: {
            userId: issueId,
            status: soStatus,
            getUserId: getUserId,
            statusArray: statusArray,
            currentPage: currentPage,
            showCount: pageSize
        },
        success: function(pi) {
            $('#loadInfo').hide();
            if (pi.status == -1){
                loginConfirm();
                return;
            }
            if (currentPage < 1){
                $('#' + selectTagId).empty();
            }
            var isLastPage = pi.orderPage.isLastPage;
            if (selectId == 'listAllOrder'){
                allIsLastPage = isLastPage;
            } else if (selectId == 'listIssueOrder'){
                issueIsLastPage = isLastPage;
            }else if (selectId == 'listNoRobOrder'){
                noRobIsLastPage = isLastPage;
            }else if (selectId == 'listRobOrder'){
                robIsLastPage = isLastPage;
            }else if (selectId == 'listFinishOrder'){
                finishIsLastPage = isLastPage;
            }
            appendOrderList(selectId,pi.orderPage);
        },
        error: function() {
            mTips('当前系统繁忙，请稍候再试');
            $('#loadInfo').hide();
        }
    });
}
/**
 * 登录确认
 */
function loginConfirm() {
    popTipShow.confirm('登录', '登录失效，请重新登录', ['确定', '取消'], function (e) {
        if ($(e.target).attr('class') != 'ok') {
            this.hide();
            return;
        }
        sessionStorage.setItem('lastRequestUrl', 'mMyServiceOrder.html');
        window.location.href = 'mUserLogin.html';
    });
}
/**
 * 添加订单列表
 * @param pageOrder 订单page对象
 */
function appendOrderList(appendId,pageOrder) {
    var poList = pageOrder.list, olDiv = $('#' + appendId), userId = sessionStorage.getItem(SCS_USER_ID);
    if (poList.length < 1){
        mTips('您还没有发布或抢服务单，快去抢单赚钱吧');
        return;
    }
    var maxNum = getTitleMaxWordNum();
    for (var g = 0; g < poList.length; g ++){
        var po = poList[g], dateImg = '<img src="../../staticFile/images/mobile/date.png">';
        var robDate = po.robDate == null ? '' : po.robDate, btnStr = '',isRob = userId == po.robUser,isIssue = userId == po.issueUser,
            isComment = po.isComment, orderFinish = (po.status == '1' && isRob) || (po.status == '4' && isIssue),
            //已完成 && (发布人或抢单人都未评价 || (发布人已评且抢单人未评 && 是抢的单) || (抢单人已评且发布人未评 && 是发布的单))
            delEvaluate = (po.status == '2' && (isComment == '0' || (isComment == '2' && isRob) || (isComment == '3' && isIssue))) ||
                (po.status == '3' && isRob) || (po.status == '7' && isIssue),
        btnDelete = '<button onclick="deleteOrder(' + po.id + ',this)">删除</button>',oName = po.name,statusName = po.statusName,
        borderCss = isRob ? 'border: 2px solid #ffab00;' : '';
        if (po.status == '0'){
            btnStr = '<button onclick="cancelOrder(' + po.id + ',this)">取消</button>';
        }else if (orderFinish){
            //抢单人完成操作
            if (po.status == '1' && isRob){
                btnStr = '<button onclick="robberDoneOrder(' + po.id + ',this)">完成</button>';
            } else if (po.status == '4' && isIssue){//发布人完成操作
                btnStr = '<button onclick="issuerDoneOrder(' + po.id + ',this)">完成</button>';
            }
        }else if (po.status == '2' && (isComment == '1' || (isComment == '2' && isIssue) || (isComment == '3' && isRob))){
            btnStr = btnDelete;
        }else if (delEvaluate){
            //已完成 && (发布人或抢单人都未评价 || (发布人已评且抢单人未评 && 是抢的单) || (抢单人已评且发布人未评 && 是发布的单))
            btnStr = btnDelete + '<button onclick="rateUser(' + po.id + ',' + (isRob ? 1 : 0) + ')">评价</button>';
        }else if (po.status == '5' || po.status == '6'){
            btnStr = btnDelete;
        }
        if (oName.length > maxNum){
            oName = oName.substring(0,maxNum) + '...';
        }
        //如果登录人是发布人，且是已抢状态，则将“已抢”改为“被抢”
        if (po.status == '1' && isIssue) {
            statusName = '被抢';
        }else if (po.status == '4' && isIssue) {
            statusName = '待我确认';//即待确认
        }
        olDiv.append('<div class="service-order" id="' + po.id + '" style="' + borderCss + '">' +
            '<div id="orderTitle">' + oName + '<span id="os_' + po.id + '" class="order-status">' + statusName + '</span></div>' +
            '<div class="order-date-type">' + dateImg + '(发)：' + po.orderDate + '<span style="float: right;">' + po.typeName + '</span></div>' +
            '<div class="order-date-type">' + dateImg + '(抢)：' + robDate + '<span style="float: right;">￥' + po.amount + '</span></div>' +
            '<div class="order-address"><div class="icon-map" style="float: left;"></div>' + po.address + '</div>' +
            '<div class="btn-group" style="text-align:right;"><button style="margin-left: 0;" onclick="orderDetail(' + po.id + ')">详情</button>' + btnStr + '</div></div>');
    }
    //如果没有下一页
    if (!pageOrder.hasNextPage) {
        olDiv.append('<div class="no-more-order"><hr/><span>没有更多订单了</span><hr/></div>');
    }

}

/**
 * 删除订单
 * @param orderId 订单ID
 */
function deleteOrder(orderId,delBtn) {
    setBtnState(delBtn,true);
    popTipShow.confirm('删除确认','删除后将不再显示，您确认要删除此订单吗？',['删 除','取 消'],function(e) {
        this.hide();
        if ($(e.target).attr('class') != 'ok') {
            setBtnState(delBtn,false);
            return;
        }
        showLoad('正在删除...');
        $.ajax({
            type: 'post',
            url: '/mServiceOrder/deleteOrder',
            dataType: 'json',
            data: {
                billId: orderId
            },
            timeout: 30000,
            success: function(r) {
                var robMsg = '订单删除失败';
                if (r == '0') {
                    robMsg = '订单删除成功';
                    $('#' + orderId).remove();
                }else if (r == '2') {
                    robMsg = '单据不存在';
                }else if (r == '3') {
                    robMsg = '单据是未抢状态，不能删除';
                }else if (r == '4') {
                    robMsg = '单据未完成，不能删除';
                }else if (r == '5') {
                    robMsg = '单据完成情况待确认，不能删除';
                }
                mTips(robMsg);
                setBtnState(delBtn,false);
                $('.loading,.page-mask').hide();
            },
            error: function() {
                mTips(errorTip);
                setBtnState(rdBtn,false);
                $('.loading,.page-mask').hide();
            }
        });
    });
}
/**
 * 取消未抢订单
 * @param cancelBillId 取消单号ID
 * @param btnCancel 取消按钮对象
 * @returns
 */
function cancelOrder(cancelBillId,btnCancel) {
    setBtnState(btnCancel,true);
    popTipShow.confirm('取消确认','取消操作将会影响您在本平台的信誉等级，您确认要取消吗？',['取 消','不 取 消'],function(e) {
        this.hide();
        if ($(e.target).attr('class') != 'ok') {
            setBtnState(btnCancel,false);
            return;
        }
        showLoad('正在取消...');
        $.ajax({
            type: 'post',
            url: '/mServiceOrder/cancelServiceOrder',
            dataType: 'json',
            data: {
                billId: cancelBillId
            },
            timeout: 30000,
            success: function(cancelResult) {
                if (cancelResult == '0') {
                    mTips('订单取消成功');
                    $('#so_' + cancelBillId).html('已取消');
                    $(btnCancel).attr('onclick','deleteOrder(' + cancelBillId + ',this)').text('删除');
                }else if (cancelResult == '2') {
                    mTips('订单不存在');
                }else if (cancelResult == '3') {
                    mTips('订单不是未抢状态');
                }else if (cancelResult == '4') {
                    mTips('该订单不是您发布的，无权取消');
                }else {
                    mTips('订单取消失败');
                }
                setBtnState(btnCancel,false);
                $('.loading,.page-mask').hide();
            },
            error: function() {
                mTips(errorTip);
                setBtnState(btnCancel,false);
                $('.loading,.page-mask').hide();
            }
        });
    });
}
/**
 * 评价用户
 * @param billId 单号ID
 * @param soType 类型，0：发布人对抢单人评价，1：抢单人对发布人评价
 * @returns
 */
function rateUser(billId, soType) {
    sessionStorage.setItem('userRateBillId', billId);
    sessionStorage.setItem('rateIssueOrRob', soType);
    window.location.href = 'mUserRate.html';
}
/**
 * 抢单人完成已抢订单
 * @param robedBillNo
 * @param btnObj
 * @returns
 */
function robberDoneOrder(orderId,rdBtn) {
    setBtnState(rdBtn,true);
    popTipShow.confirm('完成确认',doneMsg,['确 定','取 消'],function(e) {
        this.hide();
        if ($(e.target).attr('class') != 'ok') {
            setBtnState(rdBtn,false);
            return;
        }
        showLoad('正在完成操作...');
        $.ajax({
            type: 'post',
            url: '/mServiceOrder/robberDoneOrder',
            dataType: 'json',
            data: {
                billId: orderId
            },
            timeout: 30000,
            success: function(r) {
                var robMsg = '订单处理失败';
                if (r == '0') {
                    robMsg = '订单成功完成';
                    $('#os_' + orderId).html('待确认');
                    rdBtn.remove();
                }else if (r == '2') {
                    robMsg = '单据不存在';
                }else if (r == '3') {
                    robMsg = '单据不是已抢状态';
                }else if (r == '4') {
                    robMsg = '单据不是您自己抢的';
                }
                mTips(robMsg);
                setBtnState(rdBtn,false);
                $('.loading,.page-mask').hide();
            },
            error: function() {
                mTips(errorTip);
                setBtnState(rdBtn,false);
                $('.loading,.page-mask').hide();
            }
        });
    });
}
function showLoad(loadText) {
    $('#loadingWord').text(loadText);
    $('.loading,.page-mask').show();
}
/**
 * 发布人完成已抢订单
 * @param orderId 订单ID
 * @param idBtn 完成按钮对象
 * @returns
 */
function issuerDoneOrder(orderId,idBtn) {
    setBtnState(idBtn,true);
    popTipShow.confirm('完成确认',doneMsg,['确 定','取 消'],function(e) {
        this.hide();
        if ($(e.target).attr('class') != 'ok') {
            setBtnState(idBtn,false);
            return;
        }
        showLoad('正在完成操作...');
        $.ajax({
            type: 'post',
            url: '/mServiceOrder/issuerDoneOrder',
            dataType: 'json',
            data: {
                billId: orderId
            },
            timeout: 30000,
            success: function(r) {
                if (r == '0') {
                    mTips('订单已完成，快去评论一下人家吧');
                    $('#os_' + orderId).html('已完成');
                    //添加评价、删除按钮
                    $(idBtn).parent('div').append('<button onclick="rateUser(' + orderId + ',0)">评价</button>'
                        + '<button onclick="deleteOrder(' + orderId + ',this)">删除</button>');
                    idBtn.remove();
                }else if(r == '2') {
                    mTips('订单不存在');
                }else if(r == '3') {
                    mTips('订单不是待确认状态');
                }else if(r == '4') {
                    mTips('订单不是您发布的，无权操作');
                }else {
                    mTips('订单处理失败');
                }
                setBtnState(idBtn,false);
                $('.loading,.page-mask').hide();
            },
            error: function() {
                mTips(errorTip);
                setBtnState(idBtn,false);
                $('.loading,.page-mask').hide();
            }
        });
    });
}
function setBtnState(btn,isDis) {
    $(btn).attr("disabled", isDis);
    btn.style.backgroundColor = isDis ? '#cccccc' : '#ffa12d';
}
//查看订单详情
function orderDetail(orderId) {
    window.location.href = "mOrderDetail.html?id=" + orderId;
}

/**
 * 获取服务标题最大汉字/字母个数
 */
function getTitleMaxWordNum() {
    var serviceOrderWidth = $('.top-title').width() * 0.96, rem = $('html').css('font-size'),oFontSize = $('#listAllOrder').css('font-size');
    rem = parseFloat(rem.replace('px','')),oFontSize = parseFloat(oFontSize.replace('px',''));
    //serviceOrderWidth - (rem * [service-order].padding) - 3个汉字状态的宽度
    var titleMaxWidth = serviceOrderWidth - rem * 0.2 * 2 - oFontSize * 3;
    return (titleMaxWidth - 2) / oFontSize;
}